/*
 * Copyright (C) 2019 fastjrun, Inc. All Rights Reserved.
 */
package com.fastjrun.snowy.codeg.generator.processor;

import com.fastjrun.codeg.processor.BaseResponseProcessor;
import com.fastjrun.snowy.codeg.generator.Constants;
import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JCodeModel;
import com.helger.jcodemodel.JExpr;
import com.helger.jcodemodel.JInvocation;

public class SnowyResponseProcessor extends BaseResponseProcessor {

  @Override
  public void processResponse(JBlock methodBlk, JInvocation jInvocation, JCodeModel cm) {
    if (this.elementClass == null) {
      methodBlk.add(jInvocation);
      methodBlk._return(cm.ref(Constants.DEFAULT_RESPONSE_HELPER_CLASS_NAME).staticInvoke("ok"));
    } else {
      if (this.isResponseIsPage()) {
        methodBlk.decl(cm.ref(Constants.DEFAULT_PAGERESPONSE_CLASS_NAME).narrow(this.elementClass), "resultData", jInvocation);
      } else if (this.isResponseIsList()) {
        methodBlk.decl(cm.ref("java.util.List").narrow(this.elementClass), "resultData", jInvocation);
      }else{
        methodBlk.decl(this.elementClass, "resultData", jInvocation);
      }

      methodBlk.decl(
              this.responseClass,
              "result",
              cm.ref(Constants.DEFAULT_RESPONSE_HELPER_CLASS_NAME).staticInvoke("data").arg(JExpr.ref("resultData")));
      methodBlk.add(
              JExpr.ref("log").invoke("debug").arg(JExpr.lit("result={}")).arg(JExpr.ref("result")));
      methodBlk._return(JExpr.ref("result"));
    }
  }

  @Override
  public void parseResponseClass(JCodeModel cm) {
    if (this.elementClass != null) {
      if (this.isResponseIsPage()) {
        this.responseClass = cm.ref(Constants.DEFAULT_RESPONSE_CLASS_NAME).narrow(cm.ref(Constants.DEFAULT_PAGERESPONSE_CLASS_NAME).narrow(this.elementClass));
      } else if (this.isResponseIsList()) {
        this.responseClass = cm.ref(Constants.DEFAULT_RESPONSE_CLASS_NAME).narrow(cm.ref("java.util.List").narrow(this.elementClass));
      } else {
        this.responseClass = cm.ref(Constants.DEFAULT_RESPONSE_CLASS_NAME).narrow(this.elementClass);
      }
    } else {
      this.responseClass = cm.ref(Constants.DEFAULT_RESPONSE_CLASS_NAME).narrow(cm.ref("String"));
    }
  }
}
